<script setup lang="ts">
import type { DelegateRequest } from '@/api/types/workflow'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { delegateTask } from '@/api/workflow'
import ApprovalActionFooter from './components/ApprovalActionFooter.vue'
import ApprovalOpinion from './components/ApprovalOpinion.vue'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '审批委派',
    navigationBarBackgroundColor: '#ffffff',
    navigationBarTextStyle: 'black',
    backgroundColor: '#f5f5f5',
  },
})

// 页面参数
const params = ref<{ id?: string, title?: string }>({})

// 表单数据
const formData = reactive({
  selectedUser: [] as string[],
  comment: '', // 委派说明
})

// 加载状态
const loading = ref(false)

// 监听页面加载，获取参数
onLoad((options) => {
  params.value = options

  // 如果有title参数，设置导航栏标题
  if (options.title) {
    uni.setNavigationBarTitle({
      title: `${decodeURIComponent(options.title as string)}-委派`,
    })
  }
})

// 委派操作函数
async function handleDelegate() {
  console.log('审批委派操作', {
    id: params.value.id,
    delegateUser: formData.selectedUser,
    comment: formData.comment,
  })

  // 验证表单
  if (!formData.selectedUser.length) {
    uni.showToast({
      title: '请选择委派人员',
      icon: 'none',
    })
    return
  }

  try {
    loading.value = true

    // 构造请求参数
    const requestData: DelegateRequest = {
      id: params.value.id || '',
      reason: formData.comment,
      delegateUserId: formData.selectedUser,
    }

    // 调用审批委派API
    const res = await delegateTask(requestData)

    if (res.data) {
      uni.showToast({
        title: '委派成功',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
    else {
      uni.showToast({
        title: res?.msg || '委派失败，请重试',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('委派审批失败:', error)
    uni.showToast({
      title: '委派失败，请稍后重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <view class="approval-container min-h-screen bg-gray-100">
    <!-- 转派原因 -->
    <ApprovalOpinion
      v-model="formData.comment"
      :maxlength="150"
      placeholder="请输入委派说明"
      title="委派说明（选填）"
    />

    <!-- 委派人员 -->
    <SelectedUsers
      v-model="formData.selectedUser"
      title="选择委派人员"
      :required="true"
    />

    <!-- 底部操作栏 -->
    <ApprovalActionFooter
      :loading="loading"
      :disabled="!formData.selectedUser"
      @confirm="handleDelegate"
    />
  </view>
</template>
